import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class CSVFormGenerator {

    public static void main(String[] args) {
        // 表单数据
        List<List<String>> formData = Arrays.asList(
                Arrays.asList("Name", "Age", "Email"),
                Arrays.asList("John Doe", "30", "johndoe@example.com"),
                Arrays.asList("Jane Smith", "25", "janesmith@example.com"),
                Arrays.asList("Tom Johnson", "35", "tomjohnson@example.com")
        );

        // 生成CSV文件
        generateCSVForm(formData, "D://form.csv");
    }

    public static void generateCSVForm(List<List<String>> formData, String filePath) {
        try (FileWriter writer = new FileWriter(filePath)) {
            for (List<String> row : formData) {
                StringBuilder line = new StringBuilder();
                for (String field : row) {
                    // 处理字段值中的特殊字符，例如逗号、换行符等
                    line.append(escapeSpecialCharacters(field)).append(",");
                }
                // 去除最后一个逗号并换行
                line.deleteCharAt(line.length() - 1);
                line.append("\n");
                writer.write(line.toString());
            }
            System.out.println("CSV form generated successfully!");
        } catch (IOException e) {
            System.out.println("Error while generating CSV form: " + e.getMessage());
        }
    }

    public static String escapeSpecialCharacters(String field) {
        // 如果字段值中包含双引号，需要将其转义为两个双引号
        if (field.contains("\"")) {
            field = field.replace("\"", "\"\"");
        }
        // 如果字段值中包含逗号、换行符等特殊字符，需要用双引号括起来
        if (field.contains(",") || field.contains("\n") || field.contains("\r")) {
            field = "\"" + field + "\"";
        }
        return field;
    }
}


